package com.example.demo.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.server.HttpServerResponse;
import com.example.demo.common.Result;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/files")
public class FileController {
    @Value("${server.port}")
    private String port;

    private static final String ip="http://localhost:";

    //上传文件
    @PostMapping("/upload")
    public Result<?> upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();      //获取文件名
        String flag = IdUtil.fastSimpleUUID();          //生成唯一标识符
        String rootFilePath = System.getProperty("user.dir") + "/src/main/resources/files/" + flag + "_" + originalFilename;  //文件路径
        FileUtil.writeBytes(file.getBytes(), rootFilePath);  //将文件写入指定路径
        return Result.success(ip+port+"/files/"+flag);
    }

    //下载文件
    @GetMapping("/{flag}")
    public void getFiles(@PathVariable String flag, HttpServletResponse response) {
        OutputStream os;  //新建输出流
        String basePath = System.getProperty("user.dir") + "/src/main/resources/files/"; //获取文件路径
        List<String> fileNames = FileUtil.listFileNames(basePath);  //获取文件名
        String avatar = fileNames.stream().filter(name -> name.contains(flag)).findFirst().orElse(""); //获取指定标识符的文件名
        try {
            if (StrUtil.isNotEmpty(avatar)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(avatar, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + avatar);  //读取文件
                os = response.getOutputStream(); //获取输出流
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("获取文件失败");
        }
    }
}
